import { Button, Checkbox, Form, Input, Link, Message } from '@arco-design/web-react';
import { useCallback } from 'react';
import { useNavigate } from 'react-router';
import { useSetRecoilState } from 'recoil';
import { getUserInfo, doLogin } from '../../../api/personal';
import { userInfoState } from '../../../store/userInfo';

import './index.css';

const FormItem = Form.Item;

export interface LoginForm {
  username: string,
  password: string,
}

export const LoginComponent = () => {

  const [form] = Form.useForm<LoginForm>();
  const setUserInfo = useSetRecoilState(userInfoState);
  const navigate = useNavigate();

  const handleSubmit = useCallback(async (values: LoginForm) => {
    const result = await doLogin(values);
    if (result.data.code === 200) {
      localStorage.setItem('token', result.data.token);
      setUserInfo(result.data.user_info);
      Message.loading({
        content: '登陆成功，将在两秒后跳转到主页',
        duration: 2000
      });
      setTimeout(() => {
        navigate('/conversation/all');
      }, 2000);
    } else {
      Message.error(result.data.msg);
    }
  }, []);

  return <div className='login-component-wrapper'>
    <h1 className='login-component-title'>用户登录</h1>
    <Form<LoginForm> onSubmit={handleSubmit} form={form} style={{ width: 600 }}>
      <FormItem<LoginForm> rules={[{ required: true, message: '请输入用户名' }]} required field="username" label='用户名'>
        <Input placeholder='请输入用户名' />
      </FormItem>
      <FormItem<LoginForm> style={{ marginTop: '20px' }} rules={[{ required: true, message: '请输入密码' }]} required field="password" label='密码'>
        <Input placeholder='请输入密码' />
      </FormItem>
      <FormItem
        style={{ marginTop: '50px' }}
        wrapperCol={{
          offset: 5,
        }}
      >
        <Button onClick={() => { form.submit() }} type='primary' style={{ width: '475px' }}>提交</Button>
      </FormItem>
      <FormItem
        wrapperCol={{
          offset: 5,
        }}
      >

        <div style={{ width: '475px', textAlign: "center" }}> <Link href='/user/register'> 注册 </Link> </div>
      </FormItem>
    </Form>
  </div>
}
